import { Table, Button, Col, Row, Pagination, message, Space, Tooltip, Spin } from 'antd';
import { useEffect, useState, useRef } from 'react';
import styles from './index.module.scss'
import { useNavigate } from 'react-router-dom';
import { ec2Records, ec2Download, ec2Start, ec2Terminate, ec2Stop, ec2Detail } from '@/service'
import { useDispatch, useSelector } from 'react-redux';
import { saveAs } from 'file-saver';
import { useTranslation } from 'react-i18next';
import { PlayCircleTwoTone, PauseCircleTwoTone, CloseCircleTwoTone, LoadingOutlined, DownCircleOutlined, RedoOutlined, LinkOutlined, VerticalAlignBottomOutlined, ArrowRightOutlined, ExportOutlined } from '@ant-design/icons';
export default (props) => {
    const [messageApi, contextHolder] = message.useMessage();
    const [isClicked, setIsClicked] = useState(false);
    const { t, i18n } = useTranslation();
    const mainStore = useSelector(store => store.main || {});
    const iframeSrc = mainStore?.iframeSrc || null;
    const timerRef = useRef(null);
    const initState = () => ({
        total: '',
        pageSize: 10,
        pageNo: 1,
        containerList: [],
        loading: false
    }),
        navigate = useNavigate(),
        dispatch = useDispatch(),
        [state, setState] = useState(initState);
    const columns = [
        {
            title: t('menu.container.table.instanceId'),
            dataIndex: 'instanceId',
            width: 200,
            ellipsis: true,
        },
        {
            title: t('menu.container.table.state'),
            dataIndex: 'state',
            render: (state) => {
                switch (state) {
                    case 0:
                        return t('menu.container.table.state.starting');
                    case 1:
                        return t('menu.container.table.state.running');
                    case 2:
                        return t('menu.container.table.state.stopping');
                    case 3:
                        return t('menu.container.table.state.stopped');
                    case 4:
                        return t('menu.container.table.state.terminating');
                    case 5:
                        return t('menu.container.table.state.terminated');
                    default:
                        return t('menu.container.table.state.initial');
                }
            },
        },
        {
            title: t('menu.container.table.publicIpv4'),
            dataIndex: 'publicIpv4',
            width: 300,
            ellipsis: true,
        },
        {
            title: t('menu.container.table.platform'),
            dataIndex: 'platform',
        },
        {
            title: t('menu.container.table.amiName'),
            dataIndex: 'amiName',
            width: 200,
            ellipsis: true,
        },
        {
            title: t('menu.container.table.operation'),
            key: 'operation',
            fixed: 'right',
            width: 200,
            render: (_, record) => (
                <div style={{ display: 'flex', justifyContent: record.state === 0 || record.state === 2 ? 'center' : 'space-between', alignItems: 'center' }}>
                    {record.state === 0 || record.state === 2 ? (
                        // 当状态为 0 或者2 时显示 Spin 加载组件
                        <Spin
                            indicator={
                                <LoadingOutlined
                                    style={{
                                        fontSize: 24,
                                    }}
                                    spin
                                />
                            }
                        />
                    ) : (record.state === 1 || record.state === 3) && (
                        <Space size="middle">
                            {record.state === 1 && (
                                <>
                                    <Tooltip title={t('menu.containerDetail.tooltip.Pause')}>
                                        <PauseCircleTwoTone
                                            twoToneColor="#dea45c"
                                            style={{ fontSize: '24px', cursor: 'pointer' }}
                                            onClick={() => handleStop(record)}
                                        />
                                    </Tooltip>
                                    <Tooltip title={t('menu.containerDetail.tooltip.Terminate')}>
                                        <CloseCircleTwoTone
                                            twoToneColor="#e77677"
                                            style={{ fontSize: '24px', cursor: 'pointer' }}
                                            onClick={() => handleTerminate(record)}
                                        />
                                    </Tooltip>
                                    <Tooltip title={t('menu.containerDetail.tooltip.Download')}>
                                        <VerticalAlignBottomOutlined
                                            style={{ color: '#275ed8', fontSize: '24px' }}
                                            onClick={() => handleDownload(record)}
                                        />
                                    </Tooltip>
                                    <Tooltip title={t('menu.containerDetail.tooltip.OpenWindow')}>
                                        <ExportOutlined
                                            style={{ color: '#4fa883', fontSize: '22px' }}
                                            onClick={() => handleIframe(record)}
                                        />
                                    </Tooltip>
                                </>
                            )}

                            {record.state === 3 && (
                                <>
                                    <Tooltip title={t('menu.containerDetail.tooltip.Restart')}>
                                        <PlayCircleTwoTone twoToneColor="#add699" style={{ fontSize: '24px', cursor: 'pointer' }} onClick={() => handleStart(record)} />
                                    </Tooltip>
                                    <Tooltip title={t('menu.containerDetail.tooltip.Terminate')}>
                                        <CloseCircleTwoTone
                                            twoToneColor="#e77677"
                                            style={{ fontSize: '24px', cursor: 'pointer' }}
                                            onClick={() => handleTerminate(record)}
                                        />
                                    </Tooltip>
                                    <Tooltip title={t('menu.containerDetail.tooltip.Download')}>
                                        <VerticalAlignBottomOutlined
                                            style={{ color: '#275ed8', fontSize: '24px' }}
                                            onClick={() => handleDownload(record)}
                                        />
                                    </Tooltip>
                                </>
                            )}
                        </Space>
                    )}
                </div>
            ),
        }
    ];
    // 下载操作
    const handleDownload = (record) => {
        let params = { instanceDbId: record.id };
        ec2Download(params).then(res => {
            const blob = new Blob([res.data], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            let name = 'private_key.pem';
            saveAs(url, name);
        })
    };
    // 跳转操作
    const handleIframe = (record) => {
        window.open(`${API_PREFIX || ''}/callon/${record.id}/`, '_blank');
    };
    // 启动操作
    const handleStart = (record) => {
        let params = { instanceDbId: record.id };
        ec2Start(params).then(res => {
            if (res.code == 0) {
                messageApi.open({
                    type: 'success',
                    content: res?.message,
                });
                getList();
            } else {
                messageApi.open({
                    type: 'error',
                    content: res?.message,
                });
            }
        }).catch(e => {
            messageApi.open({
                type: 'error',
                content: e?.message,
            });
        });
    };

    // 终止操作
    const handleTerminate = (record) => {
        let params = { instanceDbId: record.id };
        ec2Terminate(params).then(res => {
            if (res.code == 0) {
                messageApi.open({
                    type: 'success',
                    content: res?.message,
                });
                getList();
            } else {
                messageApi.open({
                    type: 'error',
                    content: res?.message,
                });
            }
        }).catch(e => {
            messageApi.open({
                type: 'error',
                content: e?.message,
            });
        });
    };

    // 停止操作
    const handleStop = (record) => {
        let params = { instanceDbId: record.id };
        ec2Stop(params).then(res => {
            if (res.code == 0) {
                messageApi.open({
                    type: 'success',
                    content: res?.message,
                });
                getList();
            } else {
                messageApi.open({
                    type: 'error',
                    content: res?.message,
                });
            }
        }).catch(e => {
            messageApi.open({
                type: 'error',
                content: e?.message,
            });
        });
    };
    const handlePageChange = (page) => {
        setState(prevParams => ({ ...prevParams, pageNo: page }));
    };
    const handlePageSizeChange = (pageNo, pageSize) => {
        setState(prevParams => ({ ...prevParams, pageNo, pageSize }));
    };
    const goBack = () => {
        navigate('/');
    }
    const toRefresh = () => {
        setIsClicked(true);
        getList();
    }
    const getDetail = async (id) => {
        const res = await ec2Detail(id);
        if (res.code === 0) {
            setState(prevState => ({
                ...prevState,
                containerList: prevState.containerList.map(item =>
                    item.id === id ? { ...item, ...res.data } : item
                ),
            }));
            return res.data.state;
        }
    }
    const getList = () => {
        let params = {
            pageNo: state.pageNo,
            pageSize: state.pageSize
        }
        setState(prevState => ({ ...prevState, loading: true }));
        ec2Records(params).then(res => {
            if (res.code == 0) {
                setState(o => ({
                    ...o,
                    containerList: res?.data?.records || [],
                    total: res?.data?.total || 0,
                    loading: false
                }));
                const itemsToPoll = res.data.records.filter(item => item.state === 0 || item.state === 2);
                if (itemsToPoll.length > 0) {
                    timerRef.current = setInterval(async () => {
                        for (const item of itemsToPoll) {
                            if (item.state === 0 || item.state === 2) {
                                await getDetail(item.id);
                            }
                        }
                    }, 30000);
                } else {
                    clearInterval(timerRef.current);
                    timerRef.current = null;
                }
                setTimeout(() => { setIsClicked(false); }, 300);
            } else {
                messageApi.open({
                    type: 'error',
                    content: res?.msg,
                });
                setState(prevState => ({ ...prevState, loading: false }));
                setTimeout(() => { setIsClicked(false); }, 300);
            }
        }).catch(e => {
            if (e?.msg) {
                messageApi.open({
                    type: 'error',
                    content: e?.msg,
                });
            }
            setState(prevState => ({ ...prevState, loading: false }));
            setTimeout(() => { setIsClicked(false); }, 300);
        });
    }
    useEffect(() => {
        return () => {
            if (timerRef.current) {
                clearInterval(timerRef.current);
                timerRef.current = null;
            }
        };
    }, [])
    useEffect(() => {
        getList();
    }, [state.pageNo, state.pageSize, i18n.language])
    return (
        <div className='page-container'>
            < div className={styles.content}>
                <div className={styles.tableCount}>
                    <Row className={styles.titBlock}>
                        <Col span={12}>
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <div className='custom-title'>{t('menu.container.title')}</div>
                                <div style={{ position: 'relative', top: '2px', cursor: 'pointer' }} onClick={toRefresh}>
                                    <RedoOutlined
                                        className={isClicked ? styles.refreshloading : ''}
                                        style={{ fontSize: '18px', marginLeft: '20px', color: '#eb8f34', marginRight: '3px', transition: 'transform 0.3s' }}
                                    />
                                    <span style={{ color: '#eb8f34', fontSize: '16px' }}>{t('menu.container.refresh')}</span>
                                </div>
                            </div>
                        </Col>
                        <Col span={12} className={styles.RightBlcok}>
                            <Button type='primary' className='custom-btn-back' onClick={goBack}>{t('common.goback.text')}</Button>
                        </Col>
                    </Row>

                    <Table
                        columns={columns.map((column) =>
                            column.key !== 'operation'
                                ? {
                                    ...column,
                                    onCell: (record) => ({
                                        onClick: () => { navigate('/instanceDetail', { state: { id: record.id } }) },
                                        style: { cursor: 'pointer' }
                                    }),
                                    render: (text, record) => {
                                        if (column.dataIndex === 'state') {
                                            return (
                                                <Tooltip title={t('menu.containerDetail.tooltip.goDetail')}>
                                                    <span
                                                        onClick={() => navigate('/instanceDetail', { state: { id: record.id } })}
                                                        style={{ cursor: 'pointer' }}
                                                    >
                                                        {
                                                            (() => {
                                                                switch (text) {
                                                                    case 0:
                                                                        return t('menu.container.table.state.starting');
                                                                    case 1:
                                                                        return t('menu.container.table.state.running');
                                                                    case 2:
                                                                        return t('menu.container.table.state.stopping');
                                                                    case 3:
                                                                        return t('menu.container.table.state.stopped');
                                                                    case 4:
                                                                        return t('menu.container.table.state.terminating');
                                                                    case 5:
                                                                        return t('menu.container.table.state.terminated');
                                                                    default:
                                                                        return t('menu.container.table.state.initial');
                                                                }
                                                            })()
                                                        }
                                                    </span>
                                                </Tooltip>
                                            );
                                        }
                                        return (
                                            <Tooltip title={t('menu.containerDetail.tooltip.goDetail')}>
                                                <span>{text}</span>
                                            </Tooltip>
                                        );
                                    }
                                }
                                : column
                        )}
                        loading={state.loading}
                        rowKey={'id'}
                        className='custom-table'
                        pagination={false}
                        dataSource={state.containerList}
                    />

                    <div className='custom-Pagination'>
                        <Pagination
                            total={state?.total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={(totalNum) => `${t('common.pagination.totalText')} ${totalNum} ${t('common.pagination.itemText')}`}
                            align="center"
                            current={state?.pageNo}
                            defaultPageSize={state?.pageSize}
                            onChange={handlePageChange}
                            onShowSizeChange={handlePageSizeChange}
                        />
                    </div>
                </div>
            </div>
            {contextHolder}
        </div >
    )
}